[[...path]].page.tsx 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
  1. import React, { useEffect } from 'react';
  2. import EventEmitter from 'events';
  3. import {
  4. isClient, isIPageInfoForEntity, pagePathUtils, pathUtils,
  5. } from '@growi/core';
  6. import type {
  7. IDataWithMeta, IPageInfoForEntity, IPagePopulatedToShowRevision, IUser, IUserHasId,
  8. } from '@growi/core';
  9. import ExtensibleCustomError from 'extensible-custom-error';
  10. import {
  11. GetServerSideProps, GetServerSidePropsContext,
  12. } from 'next';
  13. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  14. import dynamic from 'next/dynamic';
  15. import Head from 'next/head';
  16. import { useRouter } from 'next/router';
  17. import superjson from 'superjson';
  18. import { useCurrentGrowiLayoutFluidClassName } from '~/client/services/layout';
  19. import { Comments } from '~/components/Comments';
  20. import { MainPane } from '~/components/Layout/MainPane';
  21. import { PageAlerts } from '~/components/PageAlert/PageAlerts';
  22. // import { useTranslation } from '~/i18n';
  23. import { PageContentFooter } from '~/components/PageContentFooter';
  24. import QuestionnaireModalManager from '~/components/Questionnaire/QuestionnaireModalManager';
  25. import { DrawioViewerScript } from '~/components/Script/DrawioViewerScript';
  26. import { UsersHomePageFooterProps } from '~/components/UsersHomePageFooter';
  27. import type { CrowiRequest } from '~/interfaces/crowi-request';
  28. // import { renderScriptTagByName, renderHighlightJsStyleTag } from '~/service/cdn-resources-loader';
  29. // import { useRendererSettings } from '~/stores/renderer';
  30. // import { EditorMode, useEditorMode, useIsMobile } from '~/stores/ui';
  31. import type { EditorConfig } from '~/interfaces/editor-settings';
  32. import { IPageGrantData } from '~/interfaces/page';
  33. import type { RendererConfig } from '~/interfaces/services/renderer';
  34. import type { ISidebarConfig } from '~/interfaces/sidebar-config';
  35. import type { IUserUISettings } from '~/interfaces/user-ui-settings';
  36. import type { PageModel, PageDocument } from '~/server/models/page';
  37. import type { PageRedirectModel } from '~/server/models/page-redirect';
  38. import type { UserUISettingsModel } from '~/server/models/user-ui-settings';
  39. import { useEditingMarkdown } from '~/stores/editor';
  40. import { useHasDraftOnHackmd, usePageIdOnHackmd, useRevisionIdHackmdSynced } from '~/stores/hackmd';
  41. import { useSWRxCurrentPage, useSWRxIsGrantNormalized } from '~/stores/page';
  42. import { useRedirectFrom } from '~/stores/page-redirect';
  43. import { useRemoteRevisionId } from '~/stores/remote-latest-page';
  44. import {
  45. useSelectedGrant,
  46. usePreferDrawerModeByUser, usePreferDrawerModeOnEditByUser, useSidebarCollapsed, useCurrentSidebarContents, useCurrentProductNavWidth,
  47. } from '~/stores/ui';
  48. import { useSetupGlobalSocket, useSetupGlobalSocketForPage } from '~/stores/websocket';
  49. import loggerFactory from '~/utils/logger';
  50. // import { isUserPage, isTrashPage, isSharedPage } from '~/utils/path-utils';
  51. // import GrowiSubNavigation from '../client/js/components/Navbar/GrowiSubNavigation';
  52. import { DescendantsPageListModal } from '../components/DescendantsPageListModal';
  53. import { BasicLayoutWithEditorMode } from '../components/Layout/BasicLayout';
  54. import GrowiContextualSubNavigationSubstance from '../components/Navbar/GrowiContextualSubNavigation';
  55. import type { GrowiSubNavigationSwitcherProps } from '../components/Navbar/GrowiSubNavigationSwitcher';
  56. import DisplaySwitcher from '../components/Page/DisplaySwitcher';
  57. // import { serializeUserSecurely } from '../server/models/serializers/user-serializer';
  58. // import PageStatusAlert from '../client/js/components/PageStatusAlert';
  59. import type { PageSideContentsProps } from '../components/PageSideContents';
  60. import {
  61. useCurrentUser,
  62. useIsLatestRevision,
  63. useIsForbidden, useIsNotFound, useIsSharedUser,
  64. useIsEnabledStaleNotification, useIsIdenticalPath,
  65. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  66. useDrawioUri, useHackmdUri, useDefaultIndentSize, useIsIndentSizeForced,
  67. useIsAclEnabled, useIsSearchPage, useTemplateTagData, useTemplateBodyData, useIsEnabledAttachTitleHeader,
  68. useCsrfToken, useIsSearchScopeChildrenAsDefault, useCurrentPageId, useCurrentPathname,
  69. useIsSlackConfigured, useRendererConfig,
  70. useEditorConfig, useIsAllReplyShown, useIsUploadableFile, useIsUploadableImage, useIsContainerFluid, useIsNotCreatable,
  71. } from '../stores/context';
  72. import { NextPageWithLayout } from './_app.page';
  73. import {
  74. CommonProps, getNextI18NextConfig, getServerSideCommonProps, generateCustomTitleForPage,
  75. } from './utils/commons';
  76. declare global {
  77. // eslint-disable-next-line vars-on-top, no-var
  78. var globalEmitter: EventEmitter;
  79. }
  80. const NotCreatablePage = dynamic(() => import('../components/NotCreatablePage').then(mod => mod.NotCreatablePage), { ssr: false });
  81. const ForbiddenPage = dynamic(() => import('../components/ForbiddenPage'), { ssr: false });
  82. const UnsavedAlertDialog = dynamic(() => import('../components/UnsavedAlertDialog'), { ssr: false });
  83. const PageSideContents = dynamic<PageSideContentsProps>(() => import('../components/PageSideContents').then(mod => mod.PageSideContents), { ssr: false });
  84. const GrowiSubNavigationSwitcher = dynamic<GrowiSubNavigationSwitcherProps>(() => import('../components/Navbar/GrowiSubNavigationSwitcher')
  85. .then(mod => mod.GrowiSubNavigationSwitcher), { ssr: false });
  86. const UsersHomePageFooter = dynamic<UsersHomePageFooterProps>(() => import('../components/UsersHomePageFooter')
  87. .then(mod => mod.UsersHomePageFooter), { ssr: false });
  88. const DrawioModal = dynamic(() => import('../components/PageEditor/DrawioModal').then(mod => mod.DrawioModal), { ssr: false });
  89. const HandsontableModal = dynamic(() => import('../components/PageEditor/HandsontableModal').then(mod => mod.HandsontableModal), { ssr: false });
  90. const PageStatusAlert = dynamic(() => import('../components/PageStatusAlert').then(mod => mod.PageStatusAlert), { ssr: false });
  91. const logger = loggerFactory('growi:pages:all');
  92. const {
  93. isPermalink: _isPermalink, isUsersHomePage, isTrashPage: _isTrashPage, isCreatablePage, isTopPage,
  94. } = pagePathUtils;
  95. const { removeHeadingSlash } = pathUtils;
  96. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision & PageDocument, IPageInfoForEntity>;
  97. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  98. superjson.registerCustom<IPageToShowRevisionWithMeta, IPageToShowRevisionWithMetaSerialized>(
  99. {
  100. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  101. return v?.data != null
  102. && v?.data.toObject != null
  103. && v?.meta != null
  104. && isIPageInfoForEntity(v.meta);
  105. },
  106. serialize: (v) => {
  107. return {
  108. data: superjson.stringify(v.data.toObject()),
  109. meta: superjson.stringify(v.meta),
  110. };
  111. },
  112. deserialize: (v) => {
  113. return {
  114. data: superjson.parse(v.data),
  115. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  116. };
  117. },
  118. },
  119. 'IPageToShowRevisionWithMetaTransformer',
  120. );
  121. // GrowiContextualSubNavigation for NOT shared page
  122. type GrowiContextualSubNavigationProps = {
  123. isLinkSharingDisabled: boolean,
  124. }
  125. const GrowiContextualSubNavigation = (props: GrowiContextualSubNavigationProps): JSX.Element => {
  126. const { isLinkSharingDisabled } = props;
  127. const { data: currentPage } = useSWRxCurrentPage();
  128. return (
  129. <div data-testid="grw-contextual-sub-nav">
  130. <GrowiContextualSubNavigationSubstance currentPage={currentPage} isLinkSharingDisabled={isLinkSharingDisabled}/>
  131. </div>
  132. );
  133. };
  134. const IdenticalPathPage = (): JSX.Element => {
  135. const IdenticalPathPage = dynamic(() => import('../components/IdenticalPathPage').then(mod => mod.IdenticalPathPage), { ssr: false });
  136. return <IdenticalPathPage />;
  137. };
  138. const PutbackPageModal = (): JSX.Element => {
  139. const PutbackPageModal = dynamic(() => import('../components/PutbackPageModal'), { ssr: false });
  140. return <PutbackPageModal />;
  141. };
  142. type Props = CommonProps & {
  143. currentUser: IUser,
  144. pageWithMeta: IPageToShowRevisionWithMeta | null,
  145. // pageUser?: any,
  146. redirectFrom?: string;
  147. // shareLinkId?: string;
  148. isLatestRevision?: boolean,
  149. isIdenticalPathPage?: boolean,
  150. isForbidden: boolean,
  151. isNotFound: boolean,
  152. isNotCreatable: boolean,
  153. // isAbleToDeleteCompletely: boolean,
  154. templateTagData?: string[],
  155. templateBodyData?: string,
  156. isSearchServiceConfigured: boolean,
  157. isSearchServiceReachable: boolean,
  158. isSearchScopeChildrenAsDefault: boolean,
  159. isSlackConfigured: boolean,
  160. // isMailerSetup: boolean,
  161. isAclEnabled: boolean,
  162. // hasSlackConfig: boolean,
  163. drawioUri: string | null,
  164. hackmdUri: string,
  165. noCdn: string,
  166. // highlightJsStyle: string,
  167. isAllReplyShown: boolean,
  168. isContainerFluid: boolean,
  169. editorConfig: EditorConfig,
  170. isEnabledStaleNotification: boolean,
  171. isEnabledAttachTitleHeader: boolean,
  172. // isEnabledLinebreaks: boolean,
  173. // isEnabledLinebreaksInComments: boolean,
  174. adminPreferredIndentSize: number,
  175. isIndentSizeForced: boolean,
  176. disableLinkSharing: boolean,
  177. grantData?: IPageGrantData,
  178. rendererConfig: RendererConfig,
  179. // UI
  180. userUISettings?: IUserUISettings
  181. // Sidebar
  182. sidebarConfig: ISidebarConfig,
  183. };
  184. const Page: NextPageWithLayout<Props> = (props: Props) => {
  185. // const { t } = useTranslation();
  186. const router = useRouter();
  187. const { data: currentUser } = useCurrentUser(props.currentUser ?? null);
  188. // register global EventEmitter
  189. if (isClient() && window.globalEmitter == null) {
  190. window.globalEmitter = new EventEmitter();
  191. }
  192. // commons
  193. useEditorConfig(props.editorConfig);
  194. useCsrfToken(props.csrfToken);
  195. // UserUISettings
  196. usePreferDrawerModeByUser(props.userUISettings?.preferDrawerModeByUser ?? props.sidebarConfig.isSidebarDrawerMode);
  197. usePreferDrawerModeOnEditByUser(props.userUISettings?.preferDrawerModeOnEditByUser);
  198. useSidebarCollapsed(props.userUISettings?.isSidebarCollapsed ?? props.sidebarConfig.isSidebarClosedAtDockMode);
  199. useCurrentSidebarContents(props.userUISettings?.currentSidebarContents);
  200. useCurrentProductNavWidth(props.userUISettings?.currentProductNavWidth);
  201. // page
  202. useIsLatestRevision(props.isLatestRevision);
  203. useIsContainerFluid(props.isContainerFluid);
  204. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  205. useIsForbidden(props.isForbidden);
  206. useIsNotFound(props.isNotFound);
  207. useIsNotCreatable(props.isNotCreatable);
  208. useRedirectFrom(props.redirectFrom ?? null);
  209. useIsSharedUser(false); // this page cann't be routed for '/share'
  210. useIsIdenticalPath(props.isIdenticalPathPage ?? false);
  211. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  212. useIsSearchPage(false);
  213. useTemplateTagData(props.templateTagData);
  214. useTemplateBodyData(props.templateBodyData);
  215. useIsEnabledAttachTitleHeader(props.isEnabledAttachTitleHeader);
  216. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  217. useIsSearchServiceReachable(props.isSearchServiceReachable);
  218. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  219. useIsSlackConfigured(props.isSlackConfigured);
  220. // useIsMailerSetup(props.isMailerSetup);
  221. useIsAclEnabled(props.isAclEnabled);
  222. // useHasSlackConfig(props.hasSlackConfig);
  223. useDrawioUri(props.drawioUri);
  224. useHackmdUri(props.hackmdUri);
  225. // useNoCdn(props.noCdn);
  226. useDefaultIndentSize(props.adminPreferredIndentSize);
  227. useIsIndentSizeForced(props.isIndentSizeForced);
  228. useDisableLinkSharing(props.disableLinkSharing);
  229. useRendererConfig(props.rendererConfig);
  230. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  231. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  232. useIsAllReplyShown(props.isAllReplyShown);
  233. useIsUploadableFile(props.editorConfig.upload.isUploadableFile);
  234. useIsUploadableImage(props.editorConfig.upload.isUploadableImage);
  235. const { pageWithMeta, userUISettings } = props;
  236. const pageId = pageWithMeta?.data._id;
  237. const pagePath = pageWithMeta?.data.path ?? (!_isPermalink(props.currentPathname) ? props.currentPathname : undefined);
  238. useCurrentPageId(pageId ?? null);
  239. useRevisionIdHackmdSynced(pageWithMeta?.data.revisionHackmdSynced);
  240. useRemoteRevisionId(pageWithMeta?.data.revision?._id);
  241. usePageIdOnHackmd(pageWithMeta?.data.pageIdOnHackmd);
  242. useHasDraftOnHackmd(pageWithMeta?.data.hasDraftOnHackmd ?? false);
  243. useCurrentPathname(props.currentPathname);
  244. useSWRxCurrentPage(pageWithMeta?.data ?? null); // store initial data
  245. useEditingMarkdown(pageWithMeta?.data.revision?.body);
  246. const { data: grantData } = useSWRxIsGrantNormalized(pageId);
  247. const { mutate: mutateSelectedGrant } = useSelectedGrant();
  248. useSetupGlobalSocket();
  249. useSetupGlobalSocketForPage(pageId);
  250. const growiLayoutFluidClass = useCurrentGrowiLayoutFluidClassName();
  251. const shouldRenderPutbackPageModal = pageWithMeta != null
  252. ? _isTrashPage(pageWithMeta.data.path)
  253. : false;
  254. // sync grant data
  255. useEffect(() => {
  256. const grantDataToApply = props.grantData ? props.grantData : grantData?.grantData.currentPageGrant;
  257. mutateSelectedGrant(grantDataToApply);
  258. }, [grantData?.grantData.currentPageGrant, mutateSelectedGrant, props.grantData]);
  259. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  260. useEffect(() => {
  261. const decodedURI = decodeURI(window.location.pathname);
  262. if (isClient() && decodedURI !== props.currentPathname) {
  263. const { search, hash } = window.location;
  264. router.replace(`${props.currentPathname}${search}${hash}`, undefined, { shallow: true });
  265. }
  266. }, [props.currentPathname, router]);
  267. const isTopPagePath = isTopPage(pageWithMeta?.data.path ?? '');
  268. const title = generateCustomTitleForPage(props, pagePath ?? '');
  269. const sideContents = !props.isNotFound && !props.isNotCreatable
  270. ? (
  271. <PageSideContents page={pageWithMeta?.data} />
  272. )
  273. : <></>;
  274. const footerContents = !props.isIdenticalPathPage && !props.isNotFound && pageWithMeta != null
  275. ? (
  276. <>
  277. { pagePath != null && !isTopPagePath && (
  278. <Comments pageId={pageId} pagePath={pagePath} revision={pageWithMeta.data.revision} />
  279. ) }
  280. { isUsersHomePage(pageWithMeta.data.path) && (
  281. <UsersHomePageFooter creatorId={pageWithMeta.data.creator._id}/>
  282. ) }
  283. <PageContentFooter page={pageWithMeta.data} />
  284. </>
  285. )
  286. : <></>;
  287. return (
  288. <>
  289. <Head>
  290. <title>{title}</title>
  291. </Head>
  292. <div className={`dynamic-layout-root ${growiLayoutFluidClass} h-100 d-flex flex-column justify-content-between`}>
  293. <header className="py-0 position-relative">
  294. <div id="grw-subnav-container">
  295. <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />
  296. </div>
  297. </header>
  298. <div className="d-edit-none">
  299. <GrowiSubNavigationSwitcher isLinkSharingDisabled={props.disableLinkSharing} />
  300. </div>
  301. <div id="grw-subnav-sticky-trigger" className="sticky-top"></div>
  302. <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
  303. <MainPane
  304. sideContents={sideContents}
  305. footerContents={footerContents}
  306. >
  307. <PageAlerts />
  308. { props.isIdenticalPathPage && <IdenticalPathPage />}
  309. { !props.isIdenticalPathPage && (
  310. <>
  311. { props.isForbidden && <ForbiddenPage /> }
  312. { props.isNotCreatable && <NotCreatablePage />}
  313. { !props.isForbidden && !props.isNotCreatable && <DisplaySwitcher />}
  314. </>
  315. ) }
  316. <PageStatusAlert />
  317. </MainPane>
  318. {shouldRenderPutbackPageModal && <PutbackPageModal />}
  319. </div>
  320. </>
  321. );
  322. };
  323. Page.getLayout = function getLayout(page) {
  324. return (
  325. <>
  326. <DrawioViewerScript />
  327. <BasicLayoutWithEditorMode>
  328. {page}
  329. </BasicLayoutWithEditorMode>
  330. <UnsavedAlertDialog />
  331. <DescendantsPageListModal />
  332. <DrawioModal />
  333. <HandsontableModal />
  334. <QuestionnaireModalManager />
  335. </>
  336. );
  337. };
  338. function getPageIdFromPathname(currentPathname: string): string | null {
  339. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  340. }
  341. class MultiplePagesHitsError extends ExtensibleCustomError {
  342. pagePath: string;
  343. constructor(pagePath: string) {
  344. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  345. this.pagePath = pagePath;
  346. }
  347. }
  348. // apply parent page grant fot creating page
  349. async function applyGrantToPage(props: Props, ancestor: any) {
  350. await ancestor.populate('grantedGroup');
  351. const grant = {
  352. grant: ancestor.grant,
  353. };
  354. const grantedGroup = ancestor.grantedGroup ? {
  355. grantedGroup: {
  356. id: ancestor.grantedGroup.id,
  357. name: ancestor.grantedGroup.name,
  358. },
  359. } : {};
  360. props.grantData = Object.assign(grant, grantedGroup);
  361. }
  362. async function injectPageData(context: GetServerSidePropsContext, props: Props): Promise<void> {
  363. const { model: mongooseModel } = await import('mongoose');
  364. const req: CrowiRequest = context.req as CrowiRequest;
  365. const { crowi } = req;
  366. const { revisionId } = req.query;
  367. const Page = crowi.model('Page') as PageModel;
  368. const PageRedirect = mongooseModel('PageRedirect') as PageRedirectModel;
  369. const { pageService } = crowi;
  370. let currentPathname = props.currentPathname;
  371. const pageId = getPageIdFromPathname(currentPathname);
  372. const isPermalink = _isPermalink(currentPathname);
  373. const { user } = req;
  374. if (!isPermalink) {
  375. // check redirects
  376. const chains = await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  377. if (chains != null) {
  378. // overwrite currentPathname
  379. currentPathname = chains.end.toPath;
  380. props.currentPathname = currentPathname;
  381. // set redirectFrom
  382. props.redirectFrom = chains.start.fromPath;
  383. }
  384. // check whether the specified page path hits to multiple pages
  385. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  386. if (count > 1) {
  387. throw new MultiplePagesHitsError(currentPathname);
  388. }
  389. }
  390. const pageWithMeta: IPageToShowRevisionWithMeta | null = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  391. const page = pageWithMeta?.data as unknown as PageDocument;
  392. // add user to seen users
  393. if (page != null && user != null) {
  394. await page.seen(user);
  395. }
  396. // populate & check if the revision is latest
  397. if (page != null) {
  398. page.initLatestRevisionField(revisionId);
  399. await page.populateDataToShowRevision();
  400. props.isLatestRevision = page.isLatestRevision();
  401. }
  402. if (page == null && user != null) {
  403. const templateData = await Page.findTemplate(props.currentPathname);
  404. if (templateData != null) {
  405. props.templateTagData = templateData.templateTags as string[];
  406. props.templateBodyData = templateData.templateBody as string;
  407. }
  408. // apply pagrent page grant
  409. const ancestor = await Page.findAncestorByPathAndViewer(currentPathname, user);
  410. if (ancestor != null) {
  411. await applyGrantToPage(props, ancestor);
  412. }
  413. }
  414. props.pageWithMeta = pageWithMeta;
  415. }
  416. async function injectUserUISettings(context: GetServerSidePropsContext, props: Props): Promise<void> {
  417. const { model: mongooseModel } = await import('mongoose');
  418. const req = context.req as CrowiRequest<IUserHasId & any>;
  419. const { user } = req;
  420. const UserUISettings = mongooseModel('UserUISettings') as UserUISettingsModel;
  421. const userUISettings = user == null ? null : await UserUISettings.findOne({ user: user._id }).exec();
  422. if (userUISettings != null) {
  423. props.userUISettings = userUISettings.toObject();
  424. }
  425. }
  426. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  427. const req: CrowiRequest = context.req as CrowiRequest;
  428. const { crowi } = req;
  429. const Page = crowi.model('Page') as PageModel;
  430. const { currentPathname } = props;
  431. const pageId = getPageIdFromPathname(currentPathname);
  432. const isPermalink = _isPermalink(currentPathname);
  433. const page = props.pageWithMeta?.data;
  434. if (props.isIdenticalPathPage) {
  435. props.isNotCreatable = true;
  436. }
  437. else if (page == null) {
  438. props.isNotFound = true;
  439. props.isNotCreatable = !isCreatablePage(currentPathname);
  440. // check the page is forbidden or just does not exist.
  441. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  442. props.isForbidden = count > 0;
  443. }
  444. else {
  445. props.isNotFound = page.isEmpty;
  446. props.isNotCreatable = false;
  447. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  448. if (isPermalink && page.isEmpty) {
  449. props.currentPathname = page.path;
  450. }
  451. // /path/to/page ==> /62a88db47fed8b2d94f30000
  452. if (!isPermalink && !page.isEmpty) {
  453. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  454. if (!isToppage) {
  455. props.currentPathname = `/${page._id}`;
  456. }
  457. }
  458. }
  459. }
  460. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  461. // const req: CrowiRequest = context.req as CrowiRequest;
  462. // const { crowi } = req;
  463. // const UserModel = crowi.model('User');
  464. // if (isUserPage(props.currentPagePath)) {
  465. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  466. // if (user != null) {
  467. // props.pageUser = JSON.stringify(user.toObject());
  468. // }
  469. // }
  470. // }
  471. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  472. const req: CrowiRequest = context.req as CrowiRequest;
  473. const { crowi } = req;
  474. const {
  475. appService, searchService, configManager, aclService, slackNotificationService, mailService,
  476. } = crowi;
  477. props.isSearchServiceConfigured = searchService.isConfigured;
  478. props.isSearchServiceReachable = searchService.isReachable;
  479. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  480. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  481. // props.isMailerSetup = mailService.isMailerSetup;
  482. props.isAclEnabled = aclService.isAclEnabled();
  483. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  484. props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  485. props.hackmdUri = configManager.getConfig('crowi', 'app:hackmdUri');
  486. props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  487. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  488. props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  489. props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  490. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  491. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  492. props.editorConfig = {
  493. upload: {
  494. isUploadableFile: crowi.fileUploadService.getFileUploadEnabled(),
  495. isUploadableImage: crowi.fileUploadService.getIsUploadable(),
  496. },
  497. };
  498. props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  499. props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  500. props.isEnabledAttachTitleHeader = configManager.getConfig('crowi', 'customize:isEnabledAttachTitleHeader');
  501. props.rendererConfig = {
  502. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  503. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  504. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  505. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  506. plantumlUri: process.env.PLANTUML_URI ?? null,
  507. blockdiagUri: process.env.BLOCKDIAG_URI ?? null,
  508. // XSS Options
  509. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:rehypeSanitize:isEnabledPrevention'),
  510. xssOption: configManager.getConfig('markdown', 'markdown:rehypeSanitize:option'),
  511. attrWhiteList: JSON.parse(crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:attributes')),
  512. tagWhiteList: crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:tagNames'),
  513. highlightJsStyleBorder: crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  514. };
  515. props.sidebarConfig = {
  516. isSidebarDrawerMode: configManager.getConfig('crowi', 'customize:isSidebarDrawerMode'),
  517. isSidebarClosedAtDockMode: configManager.getConfig('crowi', 'customize:isSidebarClosedAtDockMode'),
  518. };
  519. }
  520. /**
  521. * for Server Side Translations
  522. * @param context
  523. * @param props
  524. * @param namespacesRequired
  525. */
  526. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  527. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  528. props._nextI18Next = nextI18NextConfig._nextI18Next;
  529. }
  530. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  531. const req = context.req as CrowiRequest<IUserHasId & any>;
  532. const { user } = req;
  533. const result = await getServerSideCommonProps(context);
  534. // check for presence
  535. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  536. if (!('props' in result)) {
  537. throw new Error('invalid getSSP result');
  538. }
  539. const props: Props = result.props as Props;
  540. if (props.redirectDestination != null) {
  541. return {
  542. redirect: {
  543. permanent: false,
  544. destination: props.redirectDestination,
  545. },
  546. };
  547. }
  548. if (user != null) {
  549. props.currentUser = user.toObject();
  550. }
  551. try {
  552. await injectPageData(context, props);
  553. }
  554. catch (err) {
  555. if (err instanceof MultiplePagesHitsError) {
  556. props.isIdenticalPathPage = true;
  557. }
  558. else {
  559. throw err;
  560. }
  561. }
  562. await injectUserUISettings(context, props);
  563. await injectRoutingInformation(context, props);
  564. injectServerConfigurations(context, props);
  565. await injectNextI18NextConfigurations(context, props, ['translation']);
  566. return {
  567. props,
  568. };
  569. };
  570. export default Page;